const { Device, Schedule, SystemLog, User } = require('../models');
const { AppError } = require('../middlewares/errorHandler');
const { logger } = require('../utils/logger');

class DeviceController {
  // 创建设备
  async createDevice(ctx) {
    const { name, deviceId, type, location, config } = ctx.request.body;
    const userId = ctx.state.user.id;

    // 检查设备ID是否已存在
    const existingDevice = await Device.findOne({ where: { deviceId } });
    if (existingDevice) {
      throw new AppError(400, '设备ID已存在');
    }

    // 创建设备
    const device = await Device.create({
      name,
      deviceId,
      type,
      location,
      config,
      userId,
      status: 'offline'
    });

    // 记录操作日志
    await SystemLog.create({
      action: 'create_device',
      operator: userId,
      target_type: 'device',
      target_id: device.id,
      details: { device }
    });

    ctx.body = {
      status: 'success',
      data: {
        device
      }
    };
  }

  // 获取设备列表
  async getDevices(ctx) {
    const { page = 1, limit = 10, type, status } = ctx.query;
    const userId = ctx.state.user.id;
    const offset = (page - 1) * limit;

    const where = { userId };
    if (type) where.type = type;
    if (status) where.status = status;

    const { count, rows: devices } = await Device.findAndCountAll({
      where,
      limit: parseInt(limit),
      offset: parseInt(offset),
      include: [Schedule]
    });

    ctx.body = {
      status: 'success',
      data: {
        total: count,
        devices
      }
    };
  }

  // 获取单个设备
  async getDevice(ctx) {
    const { id } = ctx.params;
    const userId = ctx.state.user.id;

    const device = await Device.findOne({
      where: { id, userId },
      include: [Schedule]
    });

    if (!device) {
      throw new AppError(404, '设备不存在');
    }

    ctx.body = {
      status: 'success',
      data: {
        device
      }
    };
  }

  // 更新设备
  async updateDevice(ctx) {
    const { id } = ctx.params;
    const userId = ctx.state.user.id;
    const updateData = ctx.request.body;

    const device = await Device.findOne({
      where: { id, userId }
    });

    if (!device) {
      throw new AppError(404, '设备不存在');
    }

    // 如果更新deviceId，检查是否与其他设备冲突
    if (updateData.deviceId && updateData.deviceId !== device.deviceId) {
      const existingDevice = await Device.findOne({
        where: { deviceId: updateData.deviceId }
      });

      if (existingDevice) {
        throw new AppError(400, '设备ID已存在');
      }
    }

    await device.update(updateData);

    // 记录操作日志
    await SystemLog.create({
      action: 'update_device',
      operator: userId,
      target_type: 'device',
      target_id: device.id,
      details: { before: device, after: updateData }
    });

    ctx.body = {
      status: 'success',
      data: {
        device
      }
    };
  }

  // 删除设备
  async deleteDevice(ctx) {
    const { id } = ctx.params;
    const userId = ctx.state.user.id;

    const device = await Device.findOne({
      where: { id, userId }
    });

    if (!device) {
      throw new AppError(404, '设备不存在');
    }

    await device.destroy();

    // 记录操作日志
    await SystemLog.create({
      action: 'delete_device',
      operator: userId,
      target_type: 'device',
      target_id: device.id,
      details: { device }
    });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 绑定设备
  async bindDevice(ctx) {
    const { id } = ctx.params;
    const { userId: targetUserId } = ctx.request.body;
    const operatorId = ctx.state.user.id;

    const device = await Device.findByPk(id);
    if (!device) {
      throw new AppError(404, '设备不存在');
    }

    const targetUser = await User.findByPk(targetUserId);
    if (!targetUser) {
      throw new AppError(404, '目标用户不存在');
    }

    await device.update({ userId: targetUserId });

    // 记录操作日志
    await SystemLog.create({
      action: 'bind_device',
      operator: operatorId,
      target_type: 'device',
      target_id: device.id,
      details: { device, targetUserId }
    });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 解绑设备
  async unbindDevice(ctx) {
    const { id } = ctx.params;
    const operatorId = ctx.state.user.id;

    const device = await Device.findByPk(id);
    if (!device) {
      throw new AppError(404, '设备不存在');
    }

    const originalUserId = device.userId;
    await device.update({ userId: null });

    // 记录操作日志
    await SystemLog.create({
      action: 'unbind_device',
      operator: operatorId,
      target_type: 'device',
      target_id: device.id,
      details: { device, originalUserId }
    });

    ctx.body = {
      status: 'success',
      data: null
    };
  }

  // 获取设备状态
  async getDeviceStatus(ctx) {
    const { id } = ctx.params;
    const userId = ctx.state.user.id;

    const device = await Device.findOne({
      where: { id, userId },
      attributes: ['id', 'deviceId', 'status', 'lastHeartbeat', 'lastError']
    });

    if (!device) {
      throw new AppError(404, '设备不存在');
    }

    ctx.body = {
      status: 'success',
      data: {
        deviceStatus: device
      }
    };
  }

  // 发送设备命令
  async sendCommand(ctx) {
    const { id } = ctx.params;
    const { command, params } = ctx.request.body;
    const userId = ctx.state.user.id;

    const device = await Device.findOne({
      where: { id, userId }
    });

    if (!device) {
      throw new AppError(404, '设备不存在');
    }

    if (device.status !== 'online') {
      throw new AppError(400, '设备当前不在线');
    }

    // TODO: 实现设备命令发送逻辑
    // 这里需要集成实际的设备通信服务

    // 记录操作日志
    await SystemLog.create({
      action: 'send_command',
      operator: userId,
      target_type: 'device',
      target_id: device.id,
      details: { command, params }
    });

    ctx.body = {
      status: 'success',
      data: {
        message: '命令已发送'
      }
    };
  }
}

module.exports = new DeviceController(); 